package ldh.im.fxbase.util;

import javafx.application.Platform;
import ldh.im.fxbase.exception.ECallBack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Consumer;


public class ExceptionUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionUtil.class);

    public static <T>T catchException(ECallBack<T> callBack) {
        return catchException(callBack, (String) null);
    }

    public static <T>T catchException(ECallBack<T> callBack, String msg) {
        try {
            return callBack.callBack();
        } catch (Exception e) {
            if(msg != null) {
                FxThreadUtil.runLater(()-> DialogUtil.alert("错误", msg + "错误"));
                LOGGER.error(msg + "错误", e);
            } else {
                LOGGER.error("错误", e);
            }
        }
        return null;
    }

    public static <T>T catchException(ECallBack<T> callBack, Consumer<Exception> exceptionConsumer) {
        try {
            return callBack.callBack();
        } catch (Exception e) {
            LOGGER.error("错误", e);
            if (exceptionConsumer != null) {
                exceptionConsumer.accept(e);
            }
        }
        return null;
    }

    public static <T>T catchException(ECallBack<T> callBack, Consumer<Exception> exceptionConsumer, String errorMsg) {
        try {
            return callBack.callBack();
        } catch (Exception e) {
            LOGGER.error(errorMsg, e);
            if (exceptionConsumer != null) {
                exceptionConsumer.accept(e);
            }
        }
        return null;
    }
}
